#!/usr/bin/env python

#-*- encoding:UTF-8 -*-

# $Id$

import os

import wx
import win32com.client as wc

import wx.activex as activex

# refers to D:\ActivePython25\Lib\site-packages\wx-2.8-msw-unicode\wx\lib\pdfwin.py

#from wx.lib.activexwrapper import MakeActiveXClass
#import win32com.client.gencache

#from wx.lib.activexwrapper import MakeActiveXClass

class SASEnhancedEditor(wx.Panel):
    
    def __init__(self, parent):
        
        wx.Panel.__init__(self, parent)
        
        #saseedit = wc.Dispatch(r'SAS.EnhancedEditorCtrl.1')
        #saseedit = MakeActiveXClass(SAS.EnhancedEditorCtrl.1, eventObj = self)
        
        clstr = '{B8736777-78C6-11D2-B968-00C04F81EBEB}'
        progID = 'SAS.EnhancedEditorCtrl.1'
        
        self.saseeditor = activex.ActiveXWindow(self,
                       clsId=wx.activex.CLSID(clstr),
                       id=-1,
                       name="SAS Enhanced Editor"
                       )
        
        self.saseeditor.CallAXMethod('SetLineNumbers')
        
        self.filepath = ""
        
        #self.saseeditor.CallAXMethod('EditorOptionsDlg')
        
        
        sizer = wx.BoxSizer(wx.VERTICAL)
        
        sizer.Add(self.saseeditor, 1, wx.EXPAND | wx.ALL)
        
        self.SetSizer(sizer)
        self.SetAutoLayout(True)
        
        
    def InsertFile(self, filename):
        
        if os.path.exists(filename):
            self.saseeditor.CallAXMethod('InsertFile', filename)
        
    def OpenFile(self, filename):
        
        if os.path.exists(filename):
            self.saseeditor.CallAXMethod('OpenFile', filename)
            
    def SaveFile(self, filename):
        
        self.saseeditor.CallAXMethod('SaveFile', filename)
            
            
    def Config(self):
        
        self.saseeditor.CallAXMethod('EditorOptionsDlg')
        
        
class CreateSASEEdit(wx.MDIChildFrame):

    def __init__(self, parent, id=wx.ID_ANY, label="SAS Enhanced Editor Window", iconpath=""):
        
        wx.MDIChildFrame.__init__(self, parent, id, label)
        
        
        
        self.Centre()
        self.Maximize(True)
        
        if len(iconpath):
            self.SetIcon(wx.Icon(iconpath+'\\pycon.ico', wx.BITMAP_TYPE_ICO))
        
        
        self.auiNoteBook = wx.aui.AuiNotebook(self)
        sizer = wx.BoxSizer()
        sizer.Add(self.auiNoteBook, 1, wx.EXPAND)
        self.SetSizer(sizer)
        
        #self.panel = wx.Panel(self, -1, style = wx.NO_FULL_REPAINT_ON_RESIZE)
        #self.panel = wx.Panel(self)
        #self.saseeditor = SASEnhancedEditor(self.panel)
        #
        #sizer = wx.BoxSizer(wx.VERTICAL)
        #sizer.Add(self.saseeditor, 1, wx.EXPAND | wx.ALL)
        #self.panel.SetSizer(sizer)
        #self.panel.SetAutoLayout(True)
        
        saseeditor = self._buildSASEEditor(self.auiNoteBook, title="New SAS File")
        
        saseeditor.filepath = "New SAS File"
        
        self._buildMenu()
        
        self.Show(True)
        
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.EvtOnAuiClose)
        
        
    def EvtOnAuiClose(self, event):
        
        pass
        
        
    def _buildSASEEditor(self, notebook, title="New SAS File", select=False):
        
        saseeditor = SASEnhancedEditor(notebook)
        
        notebook.AddPage(saseeditor, title, select)
        
        
        return saseeditor
        
        
    def _buildMenu(self):
        
        [wxID_FILE_NEW,
         wxID_FILE_OPEN,
         wxID_FILE_SAVE,
         wxID_FILE_SAVEAS,
         wxID_FILE_CLOSE,
         wxID_SASCONFIG
         
        ] = [wx.NewId() for _init_ctrls in range(6)]
            
        
        menu1 = wx.Menu()
        menu1.Append(wxID_FILE_NEW, "&New", "New SAS File")
        menu1.Append(wxID_FILE_OPEN, "&Open...", "Open a SAS File")
        self.filesave = menu1.Append(wxID_FILE_SAVE, "Save", "Save SAS File")
        self.filesave.Enable(False)
        self.filesaveas = menu1.Append(wxID_FILE_SAVEAS, "&Save As...", "Save SAS File As a copy")
        self.filesaveas.Enable(False)
        self.fileclose = menu1.Append(wxID_FILE_CLOSE, "&Close", "Close SAS File")
        self.fileclose.Enable(False)
        menu1.AppendSeparator()
        self.config = menu1.Append(wxID_SASCONFIG, "Config SAS Enhanced Editor...", "Config SAS Enhanced Editor")
        self.config.Enable(False)
        
        self.GetParent().Bind(wx.EVT_MENU, self.OnNew, id=wxID_FILE_NEW)
        self.GetParent().Bind(wx.EVT_MENU, self.OnOpen, id=wxID_FILE_OPEN)
        self.GetParent().Bind(wx.EVT_MENU, self.OnSave, id=wxID_FILE_SAVE)
        self.GetParent().Bind(wx.EVT_MENU, self.OnSaveas, id=wxID_FILE_SAVEAS)
        self.GetParent().Bind(wx.EVT_MENU, self.OnClose, id=wxID_FILE_CLOSE)
        self.GetParent().Bind(wx.EVT_MENU, self.OnSASConfig, id=wxID_SASCONFIG)
        
        
        parentMenu = self.GetParent().GetMenuBar()
        #parentMenu.Append(menu1, "SAS File")
        parentMenu.Insert(1, menu1, "SAS File")
        
        
    def OnNew(self, event):
        
        saseeditor = self._buildSASEEditor(self.auiNoteBook, select=True)
        
        saseeditor.filepath = "New SAS File"
        
        self.filesave.Enable(True)
        self.filesaveas.Enable(True)
        self.fileclose.Enable(True)
        self.config.Enable(False)

        
    def OnOpen(self, event):
        
        wildcard = "SAS Program File (*.sas)|*.sas|"     \
           "SAS Log File  (*.log)|*.log|" \
           "All files (*.*)|*.*"
        
        dlg = wx.FileDialog(
            self, message="Choose a SAS Program File",
            defaultDir=os.getcwd(), 
            defaultFile="",
            wildcard=wildcard,
            style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
            )

        # Show the dialog and retrieve the user response. If it is the OK response, 
        # process the data.
        if dlg.ShowModal() == wx.ID_OK:
            # This returns a Python list of files that were selected.
            paths = dlg.GetPaths()
            
            for path in paths:
                fname = os.path.basename(path)
                saseeditor = self._buildSASEEditor(self.auiNoteBook, title=fname, select=True)
                
                saseeditor.filepath = path
                
                #saseeditor.InsertFile(path)
                saseeditor.OpenFile(path)
                
                self.filesave.Enable(True)
                self.filesaveas.Enable(True)
                self.fileclose.Enable(True)
                self.config.Enable(False)

        # Destroy the dialog. Don't do this until you are done with it!
        # BAD things can happen otherwise!
        dlg.Destroy()
    
    def OnSave(self, event):
        
        pageid = self.auiNoteBook.GetSelection()
        
        #saseeditor = self.auiNoteBook.GetPage(pageid).GetChildren()
        saseeditor = self.auiNoteBook.GetPage(pageid)
        #print saseeditor.filepath
        saseeditor.SaveFile(saseeditor.filepath)
        
        
    def OnSaveas(self, event):
        
        wildcard = "SAS Program File (*.sas)|*.sas|"     \
           "SAS Log File  (*.log)|*.log|" \
           "All files (*.*)|*.*"
                
        pageid = self.auiNoteBook.GetSelection()
        
        #saseeditor = self.auiNoteBook.GetPage(pageid).GetChildren()
        saseeditor = self.auiNoteBook.GetPage(pageid)
        #print saseeditor.filepath
        dlg = wx.FileDialog(
            self, message="Save the SAS Program File As...",
            defaultDir=os.path.dirname(saseeditor.filepath), 
            defaultFile=os.path.dirname(saseeditor.filepath),
            wildcard=wildcard,
            style=wx.SAVE | wx.CHANGE_DIR
            )

        # Show the dialog and retrieve the user response. If it is the OK response, 
        # process the data.
        if dlg.ShowModal() == wx.ID_OK:
            # This returns a Python list of files that were selected.
            path = dlg.GetPath()
            if os.path.exists(path):
                dlg2= wx.MessageDialog(self,  'File %s already exists, do you want to replace it?' % path ,
                                       'Warning',
                                       wx.YES_NO | wx.ICON_QUESTION
                                       )
                
                if dlg2.ShowModal() == wx.ID_YES:
                    
                    saseeditor.SaveFile(path)
                    
                    self.auiNoteBook.SetPageText(pageid, os.path.basename(path))
                    
                dlg2.Destroy()
                
            else:
                
                saseeditor.SaveFile(path)
                
                self.auiNoteBook.SetPageText(pageid, os.path.basename(path))
            
            
        dlg.Destroy()
        
    
    def OnClose(self, event):
        
        pageid = self.auiNoteBook.GetSelection()
        self.auiNoteBook.DeletePage(pageid)
        
        
    def OnSASConfig(self, event):
        
        pageid = self.auiNoteBook.GetSelection()
        
        saseeditor = self.auiNoteBook.GetPage(pageid)
        
        saseeditor.Config()
    
    def OnCloseWindow(self, event):
        
        # delete menu "SAS File"
        parentMenu = self.GetParent().GetMenuBar()
        
        MenuLst = [k for j, k in parentMenu.GetMenus()]
        
        pos = MenuLst.index(u"SAS File")
        
        parentMenu.Remove(pos)
        
        self.Destroy()
        
